package com.cos.services.impl;

import com.cos.dao.SysRoleMapper;
import com.cos.dao.SysUserMapper;
import com.cos.entity.SysRole;
import com.cos.entity.SysUser;
import com.cos.services.SysUserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: COS
 * @time: 2021/11/22 11:25
 * @description:
 */

//@Repository
//@Component
@Service("sysUserServicesImpl")
public class SysUserServicesImpl implements SysUserServices {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;

    /**
     * @author: COS
     * @return:
     * @time: 2021/11/22 11:26
     * @description: 认证操作的方法
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1 从数据库获取对象的数据,使用用户名查询
        SysUser sysUser = userMapper.getUserByName(username);
        if (sysUser != null) {
            //密码验证交给spring-security验证处理
            // User(String username, String password,Collection<? extends GrantedAuthority> authorities)
            //获取用户角色
            List<SysRole> userRole = roleMapper.getUserRole(sysUser.getId());
            //设置用户有的权限集合 SimpleGrantedAuthority
            List<SimpleGrantedAuthority> roles = new ArrayList<>();
            //遍历用户角色
            for (SysRole sysRole : userRole) {
                roles.add(new SimpleGrantedAuthority(sysRole.getName()));
            }
            //创建SimpleGrantedAuthority用于设置用户所拥有的权限
            //"{noop}"不加密
            System.out.println(sysUser);
            UserDetails userDetails = new User(username, sysUser.getPassword(), roles);
            return userDetails;
        }
        return null;
    }
}
